#include "GotoDeclaration.h"
#include "simodo/lsp-server/ServerContext.h"
#include "simodo/lsp-server/DocumentContext.h"

#include "simodo/variable/json/Rpc.h"
#include "simodo/variable/json/Serialization.h"
#include "simodo/inout/convert/functions.h"
#include "simodo/lsp-client/TextDocumentPositionParams.h"

namespace simodo::lsp
{

void GotoDeclaration::work()
{
    if (_jsonrpc.is_valid()) {
        lsp::TextDocumentPositionParams doc_position;
        if (lsp::parseTextDocumentPositionParams(_jsonrpc.params(), doc_position)) {
            DocumentContext * doc = _server.findDocument(doc_position.textDocument.uri);
            if (doc) {
                variable::Value result = doc->produceGotoDeclarationResponse(doc_position.position);
                _server.sending().push(variable::JsonRpc(result, _jsonrpc.id()));
                return;
            }

            _server.log().error("'textDocument/declaration' command: uri '" 
                                + doc_position.textDocument.uri + "' don't loaded yet",
                                variable::toJson(_jsonrpc.value()));
            _server.sending().push(
                /// @todo Скорректировать коды (и тексты) ошибок
                variable::JsonRpc(-1,
                    u"'textDocument/declaration' command: uri '" 
                    + inout::toU16(doc_position.textDocument.uri) + u"' don't loaded yet",
                    _jsonrpc.id()));
            return;
        }
    }
    _server.log().error("There are wrong parameter structure of 'textDocument/declaration' command", 
                        variable::toJson(_jsonrpc.value()));
    _server.sending().push(
        /// @todo Скорректировать коды (и тексты) ошибок
        variable::JsonRpc(-1,u"There are wrong parameter structure of 'textDocument/declaration' command",
                            _jsonrpc.id()));
}

}